package com.kova.api.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.kova.api.common.ResultEnum;
import com.kova.api.exception.CommonException;
import com.kova.api.model.UserInfo;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.HashMap;

public class JwtUtils {

    //过期时间
    public static final int EXPIRE_DAY = 7;
    //秘钥
    public static final  String APPSECRET = "ms8RsHmhhPsDEj6T";


    public static void main(String[] args){

        UserInfo info = new UserInfo();
        info.setUserId("1");
        info.setUserName("kingboyrang");
        String token = createToken(info);
        System.out.println("token="+token);

    }


    /**
     *  创建token
     * @param userInfo
     * @return
     */
    public static String createToken(UserInfo userInfo){
        //预设一个token过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,EXPIRE_DAY);//过期时间为7天
        String token = JWT.create()
                .withHeader(new HashMap<>())//Header
                .withClaim("userId", userInfo.getUserId())//PayLoad
                .withClaim("userName", userInfo.getUserName())
                .withExpiresAt(calendar.getTime())//过期时间
                .sign(Algorithm.HMAC256(APPSECRET));//签名用的密钥secret
        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static UserInfo resolveToken(String token){
        if (StringUtils.isEmpty(token)){
            return null;
        }
        //创建解析对象，使用的算法和secret要和创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(APPSECRET)).build();
        try {
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            if (decodedJWT!=null){
                Claim userIdString = decodedJWT.getClaim("userId");
                Claim userName = decodedJWT.getClaim("userName");
                UserInfo info = new UserInfo();
                info.setUserId(userIdString.asString());
                info.setUserName(userName.asString());
                return info;
            }
        }catch (JWTVerificationException ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 验证token
     * @param token
     */
    public static void verifyToken(String token){
        if (StringUtils.isEmpty(token)){
            throw new CommonException(ResultEnum.PARAM_ERROR.getCode(),"请求头参数token不为空");
        }
        //创建解析对象，使用的算法和secret要和创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(APPSECRET)).build();
        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException ex){
            throw new CommonException(ResultEnum.TOKEN_ERROR);
        }
    }


}
